/*
 * 文件名：OrderController.java
 * 版权：订单处理类
 * 描述：TODO
 * 修改人：zuo liubo
 * 修改时间：2013-3-5 上午9:19:16
 */
package com.scpii.api.controller.ec;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scpii.api.common.Constants;
import com.scpii.api.common.EcConstants;
import com.scpii.api.common.annoation.Pagination;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.common.exception.EcException;
import com.scpii.api.common.exception.UserIdDisaccordException;
import com.scpii.api.domain.ec.Order;
import com.scpii.api.domain.ec.ShoppingCar;
import com.scpii.api.persistence.ec.ShoppingCarMapper;
import com.scpii.api.service.ec.OrderService;
import com.scpii.api.service.ec.PayService;
import com.scpii.api.util.PrincipalUtil;

/**
 * @description 订单处理类
 * @author zuo liubo
 * @date 2013-3-5
 */
@Controller
@RequestMapping("/ec/order")
public class OrderController extends BaseController {
	private Log logger = LogFactory.getLog(OrderController.class);

	int affectRow = 0;

	@Resource
	private OrderService orderService;
	@Resource
	private PayService payService;
	@Resource
	private ShoppingCarMapper shoppingCarMapper;

	/**
	 * 根据查询条件返回订单列表
	 * 
	 * @param userId
	 *            用户ID
	 * @param order
	 *            订单信息
	 * @param type
	 *            状态0表示全部，1表示未付款 ，2表示交易中， 3表示交易成功
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
	@ResponseBody
	@Pagination
	public List<Order> getOrderList(@PathVariable("userId") Long userId, Order order,
			@RequestParam(value = "type", defaultValue = "0") Integer type) throws Exception {
		logger.info("userId = " + userId);
		Long _userId = PrincipalUtil.getPrincipal().getId();
		if (!_userId.equals(userId)) {
			throw new UserIdDisaccordException();
		}
		return orderService.selectOrdersByUserId(order, type);
	}

	/**
	 * 提交订单
	 * 
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Object insertOrderAndPayOrder(Order order, String shoppingCarId) throws Exception {
		Long userId = order.getUserId();
		Long _userId = PrincipalUtil.getPrincipal().getId();
		if (!_userId.equals(userId)) {
			throw new UserIdDisaccordException();
		}
		int paymentType = order.getPaymentType();
		// 拆分订单,并分别提交订单
		List<List<ShoppingCar>> list = splitOrder(shoppingCarId);
		List<Object> result = new ArrayList<Object>();
		for (List<ShoppingCar> listCar : list) {
			try {
				if (listCar.size() != 0) {
					order.setPaymentType(paymentType);
					Long orderId = (Long) orderService.submitOrder(order, listCar);
					result.add(payService.payOrder(orderId));
				}
			} catch (Exception e) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("orderId", order.getOrderId());
				map.put("orderSn", order.getOrderSn());
				map.put("paymentType", order.getPaymentType());
				map.put("status", 1008);
				map.put("statusDescription", "服务器内部错误");
				if(e instanceof EcException){
					map.put("status", ((EcException) e).getStatus().getValue());
					map.put("statusDescription", e.getMessage());
				}
				map.put("totalPrice", calculateTotalPrice(listCar));
				result.add(map);
			}
		}
		return result;
	}

	/**
	 * 根据提交的商品来拆分订单，其实就是将有使用积分支付的商品单独出来一个订单
	 * @param shoppingCarId	购物车ID
	 * @return	
	 */
	private List<List<ShoppingCar>> splitOrder(String shoppingCarId) {
		List<Long> carIdList = new ArrayList<Long>();
		String[] ids = shoppingCarId.split(Constants.ID_SEPARATOR);
		for (String id : ids) {
			carIdList.add(Long.parseLong(id));
		}
		List<ShoppingCar> cars = shoppingCarMapper.selectWithList(carIdList);
		List<ShoppingCar> pointList = new ArrayList<ShoppingCar>();  //使用积分支付的购物车ID
		List<ShoppingCar> cashList = new ArrayList<ShoppingCar>(); // 使用RMB支付的购物车ID
		for (ShoppingCar car : cars) {
			int paymentType = car.getProduct().getPaymentType();
			if (paymentType == EcConstants.PaymentType.PAY_POINT) {
				pointList.add(car);
			} else {
				cashList.add(car);
			}
		}
		
		List<List<ShoppingCar>> list = new ArrayList<List<ShoppingCar>>();
		list.add(cashList);
		list.add(pointList);
		return list;
	}
	
	/**
	 * 计算订单总价
	 * @param listCars	购物车
	 * @return	返回购物车中所有商品的总价
	 */
	private Float calculateTotalPrice(List<ShoppingCar> listCars){
		 float totalPrice = 0.0f;
		for(ShoppingCar car : listCars){
			totalPrice +=  car.getProduct().getPrice() * car.getQuantity();
		}
		return totalPrice;
	}
	
	
}
